from strategy.handler.BuySeller import BuySeller


# 固定股票数量的买卖方法, 每次买入固定数量(100股)的股票, 买入卖出都由策略决定
class FixedCntBuySeller(BuySeller):
    # 仅买计算方式相关变量
    position = {}

    singleCnt = 100

    def handle(self, i, signal):
        if not signal:
            return
        res = signal[0] + signal[1]
        if res > 0:
            self.buy()
        elif res < 0:
            self.sell()

    def buy(self):
        super().buy()
        cnt = self.singleCnt
        price = self.getPrice()
        self.inputAll += self.getPrice() * cnt
        self.position[self.getDate()] = cnt
        self.log('买入:{cost}'.format(cost=round(price * cnt, 2)), self.manager.tradeLogLevel)
        return

    def sell(self):
        price = self.getPrice()
        position = list(self.position.keys())
        for key in position:
            self.outputAll += self.position[key] * price
            self.log('卖出:{cost}'.format(cost=round(price * self.singleCnt, 2)), self.manager.tradeLogLevel)
            del self.position[key]

    def endTrade(self):  # 结算
        self.sell()
# rate = round((avg - buyPrice) / buyPrice, 3)
# rateSum += rate
# self.profitRate = rateSum / len(self.buy2Finish)


# 盈利率计算修订
# 盈利计算方法
# a. 盈利*买的次数/投入总金额
# b. 盈利/投入总金额
#
# 交易序号: 次数 盈利		//设每次投入1000
# 交易1: 2 800	每次赚400	a:80%, b:40%
# 交易2: 8 800	每次赚100	a:80%, b:10%
# 只要在同一个时间区间, 他们的盈利率应该是一样, 但是b盈利计算方法收益就为10%
# 交易次数越频,在*买的次数后虽然盈利会增加, 但是基数投入金额也会相应增加
